<?php
class CommonAction extends Action {
	//验证是否登录
	protected function authUser(){
		if (! $this->isLogin())
			$this->error('请先登录！谢谢！','/');
	}
	//用户是否登录，已登录返回TRUE,未登录返回FALSE
	public function isLogin() {
		$user = session('user');
		if ($this->isAjax()){
			if ($user){
				$user['user_alltimes'] 	= self::getAddTimesAll();
				$user['time_now']		= time();
				$result 				= json_encode($user);
			}else{
				$result = '0';
			}
			echo $result;
		}else{
			return (bool)$user;
		}

	}

	//获得免费添加总次数
	public function getAddTimesAll (){
		$Keywords = M('Keywords');
		if($Keywords ->where('user_id = '.$_SESSION['user']['user_id'].' AND add_time > '.strtotime(date('Y-m-d')))->find())
			$times = 0;
		else
			$times = 1;
		
		$User = M('User');
		$times = $times + (int)$User->getFieldByUserId($_SESSION['user']['user_id'], 'user_add_times');
		//$times += $_SESSION['user']['user_add_times'];
		return $times;
	}
	
	//更新免费添加次数
	protected function updateAddTimes (){
		//$Keywords = M('Keywords');
		//if($Keywords ->where('user_id = '.$_SESSION['user']['user_id'].' AND add_time > '.strtotime(date('Y-m-d')))->find()){
		//	$User = M('User');
		//	$User->where('user_id = '.$_SESSION['user']['user_id'])->setDec('user_add_times');
		//	$_SESSION['user']['user_add_times'] = $_SESSION['user']['user_add_times'] - 1;
		//}
		$User = M('User');
		$userInfo = $User->where('user_id = '.$_SESSION['user']['user_id'])->find();
		if($userInfo['user_add_times'] > 0)
		{
			$User->where('user_id = '.$_SESSION['user']['user_id'])->setDec('user_add_times');
		}
	}
	
}